package lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketSeller {
    private final ReentrantLock lock = new ReentrantLock();
    private int ticketCount = 10;

    public boolean buyTicket() {
        lock.lock();
        try {
            if (ticketCount > 0) {
                ticketCount--;
                System.out.println("成功购买一张票，剩余票数：" + ticketCount);
                return true;
            } else {
                System.out.println("票已售罄，无法购买");
                return false;
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TicketSeller ticketSeller = new TicketSeller();

        // 创建多个线程同时购买票
        Thread buyer1 = new Thread(() -> ticketSeller.buyTicket());
        Thread buyer2 = new Thread(() -> ticketSeller.buyTicket());
        Thread buyer3 = new Thread(() -> ticketSeller.buyTicket());
        buyer1.start();
        buyer2.start();
        buyer3.start();
    }
}